from elasticsearch import Elasticsearch

class ElasticSearchHelper:
    def __init__(self, es_host, es_port):
        self.es = Elasticsearch([f"http://{es_host}:{es_port}"])

    # 查询指定索引大小
    def get_index_size(self, index_name):
        """
        index_name: 索引名称
        """
        index_stats = self.es.indices.stats(index=index_name)
        index_size = index_stats['_all']['total']['store']['size_in_bytes']
        index_size_gb = index_size / 1024 / 1024 / 1024
        return index_size_gb
    
    # 查询数据
    def search_data_by_createdAt(self, index_name, query):
        # 执行查询
        result = self.es.search(index=index_name, body=query)
        data = []
        # 处理查询结果
        if result['hits']['total']['value'] > 0:
            for hit in result['hits']['hits']:
                data = hit['_source']
                print("符合条件的数据：", data)
        else:
            print("未找到符合条件的数据")
        return data

    # 删除数据
    def get_index_size(self, index_name, delete_id):
        """
        delete_id: 
        """
        self.es.delete(index=index_name, id=delete_id)
        return True

# 调用示例
es_host = '127.0.0.1'
es_port = 9200
index_name = '&haikou.air_hour_data'
es_helper = ElasticSearchHelper(es_host, es_port)

# 获取索引大小
# index_size_gb = es_helper.get_index_size(index_name)
# print(f"The size of index {index_name} is {index_size_gb:.2f} GB")

# 定义查询条件
query = {
    "query": {
        "match": {
            "id": '2022-09-01 02:00:001102A'
        }
    }
}
es_helper.search_data_by_createdAt("&haikou.air_vocs_hour_stats", query)